<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class TableNullCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:tableNull {table}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $table = humpToLine($this->argument('table'));
        if (empty($table)) return;
        $file = database_path('migrations/sql/' . $table . '.sql');
        if (!is_file($file)) return;
        $handle = file($file);
        for ($i = 3; $i < count($handle); $i++) {
            $str = strtr($handle[$i], [PHP_EOL => '']);
            if (!str_contains($str, 'VARCHAR(') && !str_contains($str, 'CHAR(')) continue;
            $field = $this->field($str);
            if ($field === 'serial_number') continue;
            $left = $this->field($handle[$i - 1]);
            $sql = "alter table `$table` modify column " . substr($str, 0, -1) . " after `$left`";
            DB::select($sql);
            DB::select("update `$table` set `$field`=null where `$field`=''");
        }
    }

    private function field(string $str): string
    {
        $str = strtr($str, [PHP_EOL => '']);
        $start = strpos($str, '`');
        $end = strpos($str, '`', $start + 1);
        return substr($str, $start + 1, $end - $start - 1);
    }
}
